# coding:utf-8

import win32com
import win32com.client
import os
from PIL import Image
import re

'''
reference <https://blog.csdn.net/qq_28304687/article/details/80721653>
          <https://docs.microsoft.com/en-us/office/vba/api/PowerPoint.PpSaveAsFileType>

presentation.SaveAs params:
    ppSaveAsPresentation                    1
    ppSaveAsTemplate                        5
    ppSaveAsRTF                             6
    ppSaveAsShow                            7
    ppSaveAsAddIn                           8
    ppSaveAsDefault                         11
    ppSaveAsMetaFile                        15
    ppSaveAsGIF                             16
    ppSaveAsJPG                             17
    ppSaveAsPNG                             18
    ppSaveAsBMP                             19
    ppSaveAsTIF                             21
    ppSaveAsEMF                             23
    ppSaveAsOpenXMLPresentation             24
    ppSaveAsOpenXMLPresentationMacroEnabled 25
    ppSaveAsOpenXMLTemplate                 26
    ppSaveAsOpenXMLTemplateMacroEnabled     27
    ppSaveAsOpenXMLShow                     28
    ppSaveAsOpenXMLShowMacroEnabled         29
    ppSaveAsOpenXMLAddin                    30
    ppSaveAsOpenXMLTheme                    31
    ppSaveAsPDF                             32
    ppSaveAsXPS                             33
    ppSaveAsXMLPresentation                 34
    ppSaveAsOpenDocumentPresentation        35
    ppSaveAsOpenXMLPicturePresentation      36
    ppSaveAsWMV                             37
    ppSaveAsStrictOpenXMLPresentation       38
    ppSaveAsMP4                             39
    ppSaveAsExternalConverter               64000

'''

root = os.getcwd()
ppt_root = root + '\\ppt\\'
jpg_root = root + '\\result\\'
# save_type = 17

def ppt2jpg(ppt_file_name):
    """
    :function:transfer ppt to jpg
    :author: shong 2018/08/20
    :param ppt_file_name: file name
    """
    powerpoint = win32com.client.Dispatch('PowerPoint.Application')
    # powerpoint.Visible = True                                    # 0-invisible,run in background;1-visible
    ppt = powerpoint.Presentations.Open(ppt_root + ppt_file_name)  # open ppt files
    ppt.SaveAs(jpg_root + ppt_file_name.rsplit('.')[0] + '.png')   # save as(file_name+file_type)
    ppt.Close()
    powerpoint.Quit()


def join_all_jpg(ppt_files_dir):
    """
    :function:join png to result.png
    :author: shong 2018/08/20
    :param ppt_files_dir: file dir
    """
    ims = [fn for fn in os.listdir(ppt_files_dir) if fn.endswith('.png')]
    # get serial number
    ims_dict = {}
    for i in ims:
        num = re.findall('\d+',i)
        if num :
            ims_dict[i] = int(num[0])
    # sorted by value
    sorted_im = sorted(ims_dict.items(), key=lambda ims_dict: ims_dict[1])
    # open image
    ims = [ Image.open(ppt_files_dir +file_name[0]) for file_name in sorted_im]
    # get width and height for module
    ws = []        # all width
    hs = []        # all height
    for per in ims:
        w,h = per.size
        ws.append(w)
        hs.append(h)
    width = max(ws)
    height = sum(hs)
    # draw result.png size
    result = Image.new(ims[0].mode,(width,height))
    current_height = 0
    for i,im in enumerate(ims):
        result.paste(im,box=(0,current_height))
        current_height += im.size[1]
    result.save(ppt_files_dir + 'result.png')
    

if __name__ == '__main__':
    file_names = [fns for fns in os.listdir(ppt_root) if fns.endswith(('.ppt', 'pptx'))]
    print '#0.Start Application.'
    print 'Totally there are {} ppt need to deal.'.format(len(file_names))
    for ppt_file_name in file_names:
        print '#1.Begin to tranfer {} to png format.'.format(ppt_file_name)
        ppt2jpg(ppt_file_name)
        print '#2.Has created png files.'
        print '#3.Start to join png.'
        join_all_jpg(jpg_root + ppt_file_name.rsplit('.')[0] +'\\')
        print '#4.Has created result png.'
    # join_all_jpg(jpg_root + u'基金行业信息化管理系统2018' +'\\')
    raw_input('Done.Press Enter to exit.')

